package com.ajk.message.service.impl;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.ajk.message.config.ConfigProperties;
import com.ajk.message.model.BaseModel;
import com.ajk.message.model.req.EaseRegisterUserReq;
import com.ajk.message.model.res.EaseAccessTokenRes;
import com.ajk.message.service.EasemobService;
import com.ajk.message.util.HttpClientUtil;
import com.google.gson.JsonObject;

/**
 * jinfang#aijiankangim
 * @author kk
 *
 */

@Service
public class EasemobServiceImpl implements EasemobService {
	
	
	Logger logger = LoggerFactory.getLogger(EasemobServiceImpl.class);
	private EaseAccessTokenRes accessToken = null;
	private String serviceURL = null;
	private String accessTokenUrl = null;
	private String regiesterUrl = null;
	
	@Autowired
	ConfigProperties configProperties;
	
	public String getAuthorization() {
		EaseAccessTokenRes tokenRes = getAccessToken();
		String token = tokenRes.getAccessToken();
		String authorization = "Bearer "+token;
		return authorization;
	}
	
	private String getServerUrl(){
		logger.info("serviceURL : {}",serviceURL);
		if(serviceURL==null){
			logger.info("serviceURL : {}",serviceURL);
			serviceURL =configProperties.getApiProtocal() + "://" + configProperties.getApiHost() + "/" + configProperties.getApiOrg() + "/" + configProperties.getApiApp();
		}
		return serviceURL;
	}
	
	public String getAccessTokenUrl() {
		if(accessTokenUrl==null){
			accessTokenUrl = getServerUrl()+"/token";
		}
		return accessTokenUrl;
	};
	
	public String getRegiesterUrl() {
		logger.info("getRegiesterUrl : {}",regiesterUrl);
		if(regiesterUrl==null){
			logger.info("getRegiesterUrl : {}",regiesterUrl);
			regiesterUrl = getServerUrl() +"/users";
		}
		return regiesterUrl;
	}

	public static <T> HttpEntity<T> getHttpEntity(T body,String[] headers){
		MultiValueMap<String, String> mheaders = new LinkedMultiValueMap<String, String>();
		if(ArrayUtils.isNotEmpty(headers) && headers.length % 2==0){
			for(int i=0; i<headers.length; i=i+2){
				mheaders.add(headers[i],headers[i+1]);
			}
		}
		HttpEntity<T> httpEntity = new HttpEntity<T>(body,mheaders);
		return httpEntity;
	}
	
	@Override
	public EaseAccessTokenRes getAccessToken() {
		if(accessToken==null || accessToken.isExpires()){
			//获取AccessToken
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("grant_type", configProperties.getGrantType());
			jsonObject.addProperty("client_id", configProperties.getAppClientId());
			jsonObject.addProperty("client_secret", configProperties.getAppClientSecret());
			String body = jsonObject.toString();
 			String result = HttpClientUtil.doPost(getAccessTokenUrl(), body, new String[]{HttpHeaders.CONTENT_TYPE,"application/json"});
 			accessToken = BaseModel.gson.fromJson(result, EaseAccessTokenRes.class);
			accessToken.dealWith();
		}
		return accessToken;
	}

	@Override
	public String registerUser(EaseRegisterUserReq user) {
		String body = BaseModel.gson.toJson(user);
		logger.info("body : {}",body);
		String result = HttpClientUtil.doPost(getRegiesterUrl(), body,new String[]{HttpHeaders.ACCEPT_CHARSET,"utf-8",HttpHeaders.CONTENT_TYPE,"application/json;chatset=utf-8",HttpHeaders.AUTHORIZATION, getAuthorization()});
		return result;
	}

	@Override
	public String getUser(String userName) {
		StringBuilder sb = new StringBuilder();
		sb.append(getRegiesterUrl()).append("/").append(userName);
		
		String result = HttpClientUtil.doGet(sb.toString(),HttpHeaders.AUTHORIZATION, getAuthorization());
		
		return result;
	}

	@Override
	public String deleteUser(String userName) {
		StringBuilder sb = new StringBuilder();
		sb.append(getRegiesterUrl()).append("/").append(userName);
		String result = HttpClientUtil.doDelete(sb.toString(),HttpHeaders.AUTHORIZATION, getAuthorization());
		return result;
	}

	@Override
	public String resetUserPassword(String userName, String newpassword) {
		StringBuilder sb = new StringBuilder();
		sb.append(getRegiesterUrl()).append("/").append(userName).append("/password");
		JsonObject poJsonObject = new JsonObject();
		poJsonObject.addProperty("newpassword", newpassword);
		String body = BaseModel.toJsonString(poJsonObject);
		
		String result = HttpClientUtil.doPut(sb.toString(),body,HttpHeaders.AUTHORIZATION, getAuthorization());
		
		return result;
	}

	@Override
	public String resetNickname(String userName, String nickname) {

		StringBuilder sb = new StringBuilder();
		sb.append(getRegiesterUrl()).append("/").append(userName);
		JsonObject poJsonObject = new JsonObject();
		poJsonObject.addProperty("nickname", nickname);
		String body = BaseModel.toJsonString(poJsonObject);
		String result = HttpClientUtil.doPut(sb.toString(),body,HttpHeaders.AUTHORIZATION, getAuthorization());
		return result;
	}

	@Override
	public String addFriend(String owner_username, String friend_username) {
		StringBuilder sb = new StringBuilder();
		sb.append(getRegiesterUrl()).append("/").append(owner_username).append("/contacts/users/").append(friend_username);
		String body = null;
		String result = HttpClientUtil.doPost(sb.toString(),body,HttpHeaders.AUTHORIZATION, getAuthorization());
		return result;
	}

	@Override
	public String deleteFriend(String owner_username, String friend_username) {
		StringBuilder sb = new StringBuilder();
		sb.append(getRegiesterUrl()).append("/").append(owner_username).append("/contacts/users/").append(friend_username);
		String result = HttpClientUtil.doDelete(sb.toString(),HttpHeaders.AUTHORIZATION, getAuthorization());
		return result;
	}
}
